﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PandoraCommon;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;

namespace Danas
{
    /// <summary>
    /// Log writer to generate a .DAT file that can be opened by the I2M Danas free application (http://www.i2m.it/download/danas_installer.jar)
    /// </summary>
    public class LogWriter : ILogWriter
    {
        #region ILogWriter Members

        /// <summary>
        /// Name of the log writer plug-in.
        /// </summary>
        /// <value></value>
        public string Name
        {
            get { return "I2M Danas DAT file exporter"; }
        }

        /// <summary>
        /// Description for the log writer plug-in.
        /// </summary>
        /// <value></value>
        public string Description
        {
            get { return "Generates a .DAT file that can be opened by the I2M Danas free application (http://www.i2m.it/download/danas_installer.jar)"; }
        }

        /// <summary>
        /// Author of this log writer plug-in.
        /// </summary>
        /// <value></value>
        public string Author
        {
            get { return "Mário Sobral (c) 2009"; }
        }

        /// <summary>
        /// Outputs the GPS from the active list of <see cref="T:GpsPosition"/>.
        /// </summary>
        /// <param name="gpsPositions"></param>
        public void WriteLog(List<GpsPosition> gpsPositions)
        {

            SaveFileDialog saveDatDialog = new SaveFileDialog();
            saveDatDialog.DefaultExt = "kml";
            saveDatDialog.FileName = "export.dat";
            saveDatDialog.Filter = "I2M Danas (*.dat)|*.dat";
            saveDatDialog.InitialDirectory = Application.StartupPath;
            saveDatDialog.OverwritePrompt = true;
            saveDatDialog.Title = this.Name;
            if (saveDatDialog.ShowDialog() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    FileInfo datFile = new FileInfo(saveDatDialog.FileName);
                    StreamWriter writer = null;

                    try
                    {
                        writer = datFile.CreateText();
                        writer.WriteLine("$IMPOS,1000,5,4,4,1,1,17,0,0,");
                        writer.WriteLine("$NEWSESSION");
                        int i = 0;
                        for (i = 0; i < gpsPositions.Count; i++)
                        {

                            GpsPosition currentPosition = gpsPositions[i];

                            StringBuilder sb = new StringBuilder("$GPS,");
                            sb.Append(i * 100);
                            sb.Append(",");
                            sb.Append("A");                                     // gprmc[2]
                            sb.Append(",");
                            sb.Append(getLatitude(currentPosition.Latitude));   // gprmc[3]
                            sb.Append(",");
                            if (currentPosition.Latitude > 0)                   // gprmc[4]
                                sb.Append("N");
                            else
                                sb.Append("S");
                            sb.Append(",");
                            sb.Append(getLongitude(currentPosition.Longitude)); // gprmc[5]
                            sb.Append(",");
                            if (currentPosition.Longitude > 0)                  // gprmc[6]
                                sb.Append("E");
                            else
                                sb.Append("W");
                            sb.Append(",");
                            sb.Append(Math.Round(currentPosition.Speed / 1.852, 1)); // gprmc[7]
                            sb.Append(",");
                            sb.Append(currentPosition.Date.Hour.ToString("00"));    // gprmc[1]
                            sb.Append(currentPosition.Date.Minute.ToString("00"));
                            sb.Append(currentPosition.Date.Second.ToString("00"));
                            sb.Append(".00");
                            sb.Append(",100");

                            writer.WriteLine(sb.ToString());
                            
                        }
                        
                        writer.WriteLine("$VALUE,0,0,0,65535,65535,65535,0.0,0.0,0.0,0.0,");
                        
                        
                    }
                    finally
                    {
                        writer.Close();
                    }
                }
                catch (Exception ex)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Error writing DAT file: " + ex.Message, this.Name);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }

                MessageBox.Show("Done !");
            }

            #region Java code

            /*
             * 
             *  public static void main(String args[])
        throws FileNotFoundException
    {
        int contarighe = 0;
        File DANASFile = new File("C:/DANASlog.dat");
        String splits[] = null;
        SelezionaFile SF = new SelezionaFile();
        File GPSFile = SF.FileScelto();
        Date data = new Date(GPSFile.lastModified());
        System.out.println(data.toString());
        Calendar cal = new GregorianCalendar();
        cal.setTime(data);
        System.out.println(cal.get(2));
        BufferedReader in = new BufferedReader(new FileReader(GPSFile));
        try
        {
            FileWriter out = new FileWriter(DANASFile);
            out.write("$NEWSESSION\n");
            do
            {
                if(!in.ready())
                    break;
                String str = in.readLine();
                if(str.startsWith("$GPRMC"))
                {
                    contarighe++;
                    System.out.println(str);
                    splits = str.split(",");
                    String riga = (new StringBuilder()).append("$GPS,").append(contarighe * 100).append(",").append(splits[2]).append(",").append(splits[3]).append(",").append(splits[4]).append(",").append(splits[5]).append(",").append(splits[6]).append(",").append(splits[7]).append(",").append(splits[1]).append(",100\n").toString();
                    out.write(riga);
                    System.out.println(splits.length);
                }
            } while(true);
            out.write((new StringBuilder()).append("$VALUE,").append(contarighe * 100).append(",127,25,65535,65535,65535,0,22,44,0\n").toString());
            out.close();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }

             * 
             * */

            #endregion

        }

        private string getLatitude(double latitude)
        {
            string result = string.Empty;

            if(latitude > 90 || latitude < -90)
                throw new Exception("Latitude must be between -90 and 90");

            string degreesDanas = Math.Truncate(latitude).ToString();
            double minutes = Math.Round(((latitude - Math.Truncate(latitude)) * 60),2);
            string minutesDanas = minutes.ToString("0.0000");

            result = (degreesDanas + minutesDanas).Replace(',','.');

            return result;
        }

        private string getLongitude(double longitude)
        {
            string result = string.Empty;

            if (longitude > 180 || longitude < -180)
                throw new Exception("Longitude must be between -180 and 180");

            string degreesDanas = Math.Truncate(longitude).ToString();
            double minutes = Math.Round(((longitude - Math.Truncate(longitude)) * 60), 2);
            string minutesDanas = minutes.ToString("0.0000");

            result = (degreesDanas + minutesDanas).Replace(',', '.');

            return result;
        }

        #endregion
    }
}
